package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.Constants;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.SendSmsUtil;
import com.zhisuo.apicenter.util.StringUtil;
import com.zhisuo.apicenter.util.TcpUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;


/**
 * 用户寄件相关操作
 */
@Controller
@RequestMapping(value = "/usermanSendMail")
public class UserManSendMailController {

    private static final Logger log = LoggerFactory.getLogger(UserManSendMailController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private ExpressManService expressManService;
    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }


    private UserManService userManService;
    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }


    /**
     * 用户寄件第一步：扫描单号，确定预约
     */
    @RequestMapping(value = "/userSetboxUsersendOrder")
    public void userSetboxUsersendOrder(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("userSetboxUsersendOrder-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        //快递单号列表
        String paymengcodelist = jsonObject.getString("paymengcodelist");
        //包裹数量
        String boxnum = jsonObject.getString("boxnum");
        //寄件手机
        String sendmobile = jsonObject.getString("sendmobile");
        //寄件地址
        String buildid = jsonObject.getString("buildid");
        //寄件开始时间
        String senduserorderstarttime = jsonObject.getString("senduserorderstarttime");
        //寄件结束时间
        String senduserorderendtime = jsonObject.getString("senduserorderendtime");
        //寄件码
        String sendcode= RandomStringUtils.random(4, "1234567890");

        //根据所选addressid获取这个地址园区所属的收件车
        //ZhiSuoUserAddress userAddress=userManService.getZhiSuoUserAddressById(Integer.parseInt(senduseraddressid));
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(Integer.parseInt(buildid));
        List<String> listcarid=userManService.getSendZhiSuoCarByAreaId(buildinfo.getParkareaid());
        if(!(listcarid !=null && listcarid.size()>0)){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "车子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }
        ZhiSuoCar car = null;
        ZhiSuoCar sendcar = null;
        //选收件车 默认选择第一辆
        for(String allcarid:listcarid){

            car = expressManService.getCarByCarId(Integer.parseInt(allcarid));
            if(car != null){
                if(car.getType()==0){
                    sendcar=car;
                    break;
                }

            }

        }

        if(sendcar==null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "车子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }


        List<ZhiSuoCarBox> listhasZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(sendcar.getId()+"");
        if(listhasZhiSuoCarBox==null ||listhasZhiSuoCarBox.size()==0){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "箱子不存在");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        ZhiSuoCarBox box =listhasZhiSuoCarBox.get(0);
        //生成收件单
        String orderid=userManService.insertNewUserSendOrder(userid,sendcar.getId()+"",boxnum,box.getId(),box.getCode(),sendmobile,buildid,buildinfo.getCode(),senduserorderstarttime,senduserorderendtime,sendcode);

        String[] list=paymengcodelist.split(",");
        for(String code:list){
            userManService.insertNewSendOrderList(orderid,code);
        }

//        String[] params = new String[]{sendcode};
//        String[] phoneNumbers =new String[]{sendmobile};
//        //发送短信
//        SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
        userManService.insertNewZhiSuoCarNextStopSms(sendcode,sendmobile,sendcar.getId()+"",2);


        resultObj.put("error_code",0);
        resultObj.put("error_msg", "预约成功");
        resultObj.put("data","");
        responseData(resultObj.toString(), resp);
    }




    /**
     * 用户扫码寄件
     */
    @RequestMapping(value = "/getSendOrderByCarIdId")
    public void getSendOrderByCarIdId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getReceiptOrderByCarIdId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String sn = jsonObject.getString("sn");

        String mobile=userManService.getMobilByUserId(userid);
        ZhiSuoCar car=expressManService.getCarByQrcode(sn);

        if(car==null){
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "二维码已失效，请重新扫码");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }

        SendOrder order=userManService.getSendOrderIdByCarIdAndMobile(car.getId()+"",mobile);


        if(order!=null){
            //直接打开门
            //下发开箱指令
            //获取TCP服务器地址
            String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");
            List<ZhiSuoCarBox> listZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(order.getCarid()+"");
            String tcpresult= TcpUtil.openSendDoor(car,order,listZhiSuoCarBox,tcp_url);



            JSONObject oneboxjson=null;
            JSONArray opendoorarray=new JSONArray();
            for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
                oneboxjson=new JSONObject();
                Boolean flag=false;
                if(order.getBoxcode().equals(carbox.getName())){
                    flag=true;
                }else{
                    flag=false;
                }

                if(flag){
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","1");
                    oneboxjson.put("pos",carbox.getPos());
                }else{
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","0");
                    oneboxjson.put("pos",carbox.getPos());
                }
                opendoorarray.add(oneboxjson);
            }



            userManService.updateOrderBySendcode(order.getId()+"",userid);
//            //更新箱子状态
//            expressManService.updateCarBoxStatusByCode(order.getBoxcode(),order.getCarid()+"");
            //下发发车指令
            String nextstop=userManService.getNextStopByCarId(car.getId());
            String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
            if(StringUtils.isEmpty(nextstop)){
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),car.getHomestation(),stop_timeout_sec,"");
            }else{
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop_timeout_sec,"");
            }


            //根据下一站指令，获取下一个用户
            List<SendOrder> listNextStopDeliveryOrder=expressManService.getListNextSendOrderByNextStop(nextstop,car.getId()+"");



            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                for(SendOrder nextorder:listNextStopDeliveryOrder){
                    String[] params = new String[]{nextorder.getSendcode()};
                    String[] phoneNumbers =new String[]{nextorder.getSendmobile()};
                    //发送短信
                    SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                    userManService.insertNewZhiSuoCarNextStopSms(nextorder.getSendcode(),nextorder.getSendmobile(),nextorder.getCarid()+"",0);
                    //订单状态置为1
                    userManService.updateSendOrderStatusByOrderId(nextorder.getId());
                }
            }


            resultObj.put("error_code",0);
            resultObj.put("error_msg", "取件成功，关好仓门");
            resultObj.put("data",opendoorarray);
        }else{
            //取件码开门
            resultObj.put("error_code",1);
            resultObj.put("error_msg", "收件码开门");
            resultObj.put("data",car.getId());

        }
        responseData(resultObj.toString(), resp);
    }



    /**
     * 寄件码开门
     */
    @RequestMapping(value = "/setSendOrderByCode")
    public void setSendOrderByCode(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setSendOrderByCode-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String carid = jsonObject.getString("carid");
        String sendcode = jsonObject.getString("sendcode");

        String orderid =userManService.getOrderIdByCarIdAndSendcode(carid,sendcode);





        if(StringUtils.isNotEmpty(orderid)){





            //打开仓门
//            //下发开箱指令
            DeliveryOrder order=userManService.getDeliveryOrderById(orderid);


            //更新箱子状态
//            expressManService.updateCarBoxStatusByCode(order.getBoxcode(),order.getCarid()+"");
            //获取TCP服务器地址
            String tcp_url=apiService.getTcpUrlByTcpCenterUrl("tcp_center_url");







            ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));
            List<ZhiSuoCarBox> listZhiSuoCarBox=expressManService.getListZhiSuoCarBoxByCarId(order.getCarid()+"");
            String tcpresult= TcpUtil.openDoor(car,order,listZhiSuoCarBox,tcp_url);



            JSONObject oneboxjson=null;
            JSONArray opendoorarray=new JSONArray();
            for(ZhiSuoCarBox carbox:listZhiSuoCarBox){
                oneboxjson=new JSONObject();
                Boolean flag=false;
                if(order.getBoxcode().equals(carbox.getName())){
                    flag=true;
                }else{
                    flag=false;
                }

                if(flag){
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","1");
                    oneboxjson.put("pos",carbox.getPos());
                }else{
                    oneboxjson.put("code",carbox.getName());
                    oneboxjson.put("isopen","0");
                    oneboxjson.put("pos",carbox.getPos());
                }
                opendoorarray.add(oneboxjson);
            }


            userManService.updateOrderByReceiptcode(orderid,userid);

            //下发发车指令
            String nextstop=userManService.getNextStopByCarId(car.getId());
            String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
            if(StringUtils.isEmpty(nextstop)){
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),car.getHomestation(),stop_timeout_sec,"");
            }else{
                userManService.insertNewZhiSuoCarNextStopTcp(car.getSn(),car.getId(),car.getName(),nextstop,stop_timeout_sec,"");
            }




            //根据下一站指令，获取下一个用户
            List<SendOrder> listNextStopDeliveryOrder=expressManService.getListNextSendOrderByNextStop(nextstop,car.getId()+"");



            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                for(SendOrder nextorder:listNextStopDeliveryOrder){
                    String[] params = new String[]{nextorder.getSendcode()};
                    String[] phoneNumbers =new String[]{nextorder.getSendmobile()};
                    //发送短信
                    SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                    userManService.insertNewZhiSuoCarNextStopSms(nextorder.getSendcode(),nextorder.getSendmobile(),nextorder.getCarid()+"",0);
                    //订单状态置为1
                    userManService.updateSendOrderStatusByOrderId(nextorder.getId());
                }
            }

            resultObj.put("error_code",0);
            resultObj.put("error_msg", "取件成功，关好仓门");
            resultObj.put("data",opendoorarray);
        }else{
            resultObj.put("error_code",1);
            resultObj.put("error_msg", "寄件码错误或本车不收取该快递");
            resultObj.put("data","");

        }
        responseData(resultObj.toString(), resp);
    }


    /**
     * 获取用户端待寄件列表 0待寄件  1收件中  2已寄包裹
     */
    @RequestMapping(value = "/getSendOrderListById")
    public void getSendOrderListById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSendOrderListById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String status = jsonObject.getString("status");
        Integer page = jsonObject.getInteger("page");
        ZhiSuoUser user=apiService.getUserInfoByUserId(userid);

        //第一步，通过用户手机号，查询待派件列表中是否存在该用户订单
        List<SendOrder> listDeliveryOrder=userManService.getListSendOrderByReceiptMobile(user.getId()+"",status,page, Constants.PAGESIZE);
        JSONArray jsonArray=new JSONArray();
        JSONObject jo=null;
        //第二步：生成用户的待预约取件订单列表
        if(listDeliveryOrder != null &&listDeliveryOrder.size()>0){

            for(SendOrder order:listDeliveryOrder){
                //通过手机号查询用户ID
                //Integer receiptuserid=apiService.getUserIdByMobile(order.getReceiptusermobile());
                jo=new JSONObject();
                ZhiSuoCar car=expressManService.getCarByCarId(order.getCarid());
                String parkareaid=expressManService.getParkareaidByCarId(car.getId());
                String parkAreaName= expressManService.getParkAreaNameById(parkareaid);
                ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(order.getSenduseraddressid());
                jo.put("carid",car.getId());
                jo.put("carname",car.getName());
                jo.put("parkareaname",parkAreaName);
                jo.put("buildname",buildinfo.getName());
                jo.put("paymnetcompany",order.getPaymentcompany());
                jo.put("paymentcode",order.getPaymentcode());
                jo.put("create_time",order.getCreate_time());
                jo.put("orderid",order.getId());
                jo.put("senduserorderstarttime",order.getSenduserorderstarttime());
                jo.put("senduserorderendtime",order.getSenduserorderendtime());
                jo.put("boxnum",order.getBoxnum());
                jsonArray.add(jo);
            }
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);


    }


    /**
     * 根据OrderId获取订单详情
     */
    @RequestMapping(value = "/getSendOrderDetailById")
    public void getSendOrderDetailById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSendOrderDetailById-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String orderid = jsonObject.getString("orderid");

        SendOrder order=userManService.getSendOrderById(orderid);


        JSONObject jo=new JSONObject();

        ZhiSuoCar car=expressManService.getCarByCarId(order.getCarid());
        String parkareaid=expressManService.getParkareaidByCarId(car.getId());
        String parkAreaName= expressManService.getParkAreaNameById(parkareaid);
        jo.put("carid",car.getId());
        jo.put("carname",car.getName());
        jo.put("parkareaname",parkAreaName);
        jo.put("boxname",order.getBoxcode());
        jo.put("paymentcode",order.getPaymentcode());
        jo.put("create_time",order.getCreate_time());
        jo.put("paymnetcompany",order.getPaymentcompany());
        jo.put("orderid",order.getId());
        jo.put("boxnum",order.getBoxnum());
        jo.put("customermobile","021-60677608");
////        ZhiSuoUser user=userManService.getZhiSuoUserByMobile(order.getReceiptusermobile());
////        ZhiSuoUserAddress address=userManService.getZhisuoFlagUserAddressByUserId(user.getId());
//        ParkAreaBuild build=userManService.getParkAreaBuildById(order.getSenduseraddressid());
//        ParkArea area=userManService.getParkAreaById(build.getParkareaid());
//        JSONObject addressjson=new JSONObject();
//        addressjson.put("addressid",address.getId());
//        addressjson.put("flag",address.getFlag());
//        addressjson.put("parkareaname",area.getName());
//        addressjson.put("parkareabuildname",build.getName());
//        addressjson.put("parkareabuildid",address.getParkareabuildid());
//        jo.put("addressjson",addressjson);


        ZhiSuoCarStatus carstatus=expressManService.getCarStatusByCarVin(car.getSn());
        if(carstatus!=null){
            jo.put("lng",carstatus.getPositionlon()+"");
            jo.put("lat",carstatus.getPositionlat()+"");
            jo.put("heading",carstatus.getPositionheading()+"");
            jo.put("speedvalue",carstatus.getSpeedvalue()+"");
            jo.put("speedunit",carstatus.getSpeedunit()+"");
            jo.put("remaintotal",carstatus.getRemaintotal()+"");
            jo.put("remainminute","5分钟");
            if(StringUtils.isNotEmpty(carstatus.getPositionstop())){
                if(carstatus.getPositionstop().equals(car.getHomestation())){
                    jo.put("ishomestation",1);
                }else{
                    jo.put("ishomestation",0);
                }
            }else{
                jo.put("ishomestation",0);
            }
        }else{
            jo.put("lng","121.17403723382593");
            jo.put("lat","31.147796227532314");
            jo.put("heading","");
            jo.put("speedvalue","");
            jo.put("speedunit","");
            jo.put("remaintotal","");
            jo.put("remainminute","");
            jo.put("ishomestation",1);
        }

        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jo);
        responseData(resultObj.toString(), resp);



    }





    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
